<?php
/**
 * mysql connection
 */
function db_connect($sDatabase, $sUser='DEFAULT')
{
   global $__DB;
   $sDsn = '__DSN_'.strtoupper($sDatabase).'_'.strtoupper($sUser);
   if (!defined($sDsn)) { die("Dsn missing: {$sDsn}"); }
   $rDsn = parse_url(constant($sDsn));
   $__DB = mysql_connect($rDsn['host'], $rDsn['user'], $rDsn['pass']) or die("Could not connect to MySQL: ".mysql_error());
   mysql_select_db(str_replace('/', '', $rDsn['path'])) or die("Could not select the database: ".mysql_error());
   mysql_query("SET NAMES {$rDsn['scheme']}");
}

/**
 * return first data of first record
 */
function db_one($sQ)
{
   $hR = mysql_query($sQ);
   if (!is_resource($hR)) { return false; }
   $r = mysql_fetch_row($hR);
   mysql_free_result($hR);
   return $r[0];
}

/**
 * return an array of first record
 * indexed by field name
 */
function db_assoc($sQ)
{
   $hR = mysql_query($sQ);
   if (!is_resource($hR)) { return array(); }
   $r = mysql_fetch_assoc($hR);
   mysql_free_result($hR);
   return $r;
}

/**
 * return an array of first record
 * indexed by number 0,1,2...
 */
function db_row($sQ)
{
   $hR = mysql_query($sQ);
   if (!is_resource($hR)) { return array(); }
   $r = mysql_fetch_row($hR);
   mysql_free_result($hR);
   return $r;
}

/**
 * return a 2-dimension array of records
 * 1st dimension key is set defaultly to 0,1,2...
 * or set it to data of one column
 * attension: some records will be overwritten of they has the same key
 */
function db_table($sQ, $sKeyColumn='_RANK_')
{
   $hR = mysql_query($sQ);
   if (!is_resource($hR)) { return array(); }
   $rTable = array();
   $nRank = 0;
   while ($r = mysql_fetch_assoc($hR))
   {
      if ('_RANK_' == $sKeyColumn) { $sKey = $nRank; }
      else { $sKey = $r[$sKeyColumn]; }
      $rTable[$sKey] = $r;
      $nRank++;
   }
   mysql_free_result($hR);
   return $rTable;
}

/**
 * used by INSERT,UPDATE,DELETE,REPLACE
 * return number of affected rows
 */
function db_write($sQ)
{
   mysql_query($sQ);
   return mysql_affected_rows();
}

/**
 * same as mysql_query()
 * just to beautify codes
 */
function db_query($sQ)
{
   return mysql_query($sQ);
}

/**
 * same as mysql_insert_id()
 * just to beautify codes
 */
function db_insert_id()
{
   return mysql_insert_id();
}

?>
